<template>
  <div class="app-container">
     <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="会员id" prop="memId">
          <el-input
            v-model="queryParams.memId"
            placeholder="请输入会员id"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      <el-form-item label="会员姓名" prop="realname">
          <el-input
            v-model="queryParams.realname"
            placeholder="请输入会员姓名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input
            v-model="queryParams.mobile"
            placeholder="请输入手机号码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>


        <el-form-item>
           <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
           <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
     </el-form>

     <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
           <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['member:index:add']"
           >新增</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
           <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:post:edit']"
           >修改</el-button>
        </el-col>
        <el-col :span="1.5">
           <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:post:remove']"
           >删除</el-button>
        </el-col> -->
        <!-- <el-col :span="1.5">
           <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['goods:index:export']"
           >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
     </el-row>

     <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">

        <el-table-column
          label="会员id"
          align="center"
          prop="memId"
          :show-overflow-tooltip="true"
          width="80"
          fixed
        />

        <el-table-column
          label="会员姓名"
          align="center"
          prop="realname"
          :show-overflow-tooltip="true"
          width="120"
          fixed
        />
        <el-table-column
          label="手机号码"
          align="center"
          prop="mobile"
          :show-overflow-tooltip="true"
          width="120"
          fixed
        />
        <el-table-column
          label="昵称"
          align="center"
          prop="nickname"
          :show-overflow-tooltip="true"
          width="120"
        />
        <el-table-column
          label="邀请人"
          align="center"
          prop="inviterName"
          :show-overflow-tooltip="true"
          width="120"
        />
        <el-table-column
          label="会员等级"
          align="center"
          prop="memberLevelName"
          :show-overflow-tooltip="true"
          width="100"
        />
        <el-table-column label="状态" align="center" prop="status"  width="100">
           <template #default="scope">
              <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
           </template>
        </el-table-column>
        <el-table-column label="提现状态" align="center" prop="isWithdraw" width="100">
           <template #default="scope">
              <dict-tag :options="sys_normal_disable" :value="scope.row.isWithdraw" />
           </template>
        </el-table-column>
        <el-table-column
          label="会员余额(元)"
          align="center"
          prop="money"
          :show-overflow-tooltip="true"
          width="100"
        />
        <el-table-column
          label="饭团"
          align="center"
          prop="profit"
          :show-overflow-tooltip="true"
          width="80"
        />
        <el-table-column
          label="奖金池"
          align="center"
          prop="profitPool"
          :show-overflow-tooltip="true"
          width="100"
        />
        <el-table-column
          label="饭券"
          align="center"
          prop="scoreProfit"
          :show-overflow-tooltip="true"
          width="80"
        />
        <el-table-column
          label="广告积分"
          align="center"
          prop="score"
          :show-overflow-tooltip="true"
          width="80"
        />
        <el-table-column
          label="饭点"
          align="center"
          prop="dotNum"
          :show-overflow-tooltip="true"
          width="80"
        />
        <el-table-column
          label="贡献值"
          align="center"
          prop="contributionValue"
          :show-overflow-tooltip="true"
          width="80"
        />
        <el-table-column
          label="贡献值积分"
          align="center"
          prop="contributionCredit"
          :show-overflow-tooltip="true"
          width="90"
        />
        <!-- <el-table-column
          label="性别"
          align="center"
          prop="mobile"
          :show-overflow-tooltip="true"
          width="80"
        >
            <template #default="scope">
                <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
            </template>
        </el-table-column> -->


        <el-table-column label="创建时间" align="center" prop="createTime" width="200">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="详细地址"
          align="center"
          prop="address"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="操作" width="220" align="center" fixed="right" class-name="small-padding fixed-width">
           <template #default="scope">
            <el-tooltip content="修改" placement="top" >
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['member:index:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" >
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['member:index:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="充值/消费" placement="top" >
              <el-button link type="primary" icon="Coin" @click="handleRecharge(scope.row)" v-hasPermi="['member:index:recharge']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改邀请人" placement="top" >
              <el-button link type="primary" icon="User" @click="changePersons(scope.row)" v-hasPermi="['member:index:changePerson']"></el-button>
            </el-tooltip>
            <el-tooltip content="变动日志" placement="top" >
              <el-button link type="primary" icon="ChatLineSquare" @click="handleChange(scope.row)" v-hasPermi="['member:index:log']"></el-button>
            </el-tooltip>
            <el-tooltip content="拨款" placement="top" >
              <el-button link type="primary" icon="Switch" @click="handleTransform(scope.row)" v-hasPermi="['member:index:transform']"></el-button>
            </el-tooltip>
           </template>
        </el-table-column>
     </el-table>

     <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
     />

     <!-- 添加或修改会员等级对话框 -->
     <el-dialog :title="title" v-model="open" width="800px" append-to-body>
        <div class="form_box">
          <el-form ref="memberRef" :model="form" :rules="rules" label-width="100px">
            <el-row>

            <el-col :span="12">
              <el-form-item label="会员姓名" prop="realname">
                <el-input v-model="form.realname" placeholder="请输入名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邀请人" v-if="title=='添加会员'">
                <el-select
                    v-model="form.inviterId"
                    filterable
                    clearable
                    remote
                    reserve-keyword
                    placeholder="请输入手机号"
                    style="width: 290px;"
                    :remote-method="remoteMethod"
                    :loading="memloading">
                    <el-option
                      v-for="item in memberOptions"
                      :key="item.memId"
                      :label="item.realname+'('+item.mobile+')'"
                      :value="item.memId">
                    </el-option>
                  </el-select>
                </el-form-item>

            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="mobile">
                <el-input v-model="form.mobile" placeholder="请输入手机号码" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="form.nickname" placeholder="请输入昵称" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-select v-model="form.sex" placeholder="请选择性别"   style="width: 290px;">
                    <el-option
                        v-for="dict in sys_user_sex"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="会员等级" prop="memberLevel">
                <el-select v-model="form.memberLevel" placeholder="请选择会员等级"   style="width: 290px;">
                    <el-option
                        v-for="dict in memberLevelColumnList"
                        :key="dict.id"
                        :label="dict.name"
                        :value="dict.id"
                    ></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
                <el-form-item label="状态">
                  <el-radio-group v-model="form.status">
                      <el-radio
                      v-for="dict in sys_normal_disable"
                      :key="dict.value"
                      :label="dict.value"
                      >{{dict.label}}</el-radio>
                  </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="提现状态">
                  <el-radio-group v-model="form.isWithdraw">
                      <el-radio
                      v-for="dict in sys_normal_disable"
                      :key="dict.value"
                      :label="dict.value"
                      >{{dict.label}}</el-radio>
                  </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="合伙人">
                  <el-radio-group v-model="form.partner">
                    <el-radio
                      v-for="dict in partnerList"
                      :key="dict.value"
                      :label="dict.value"
                      >{{dict.label}}</el-radio>
                  </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="详细地址" prop="address">
                <el-input v-model="form.address" type="textarea" placeholder="请输入详细地址"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="个人简介" prop="intro">
                <el-input v-model="form.intro" type="textarea" placeholder="请输入个人简介"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="个人签名" prop="signature">
                <el-input v-model="form.signature" type="textarea" placeholder="请输入个人签名"></el-input>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
        </div>

        <template #footer>
           <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
           </div>
        </template>
     </el-dialog>
     <el-dialog title="充值/消费" v-model="rechargeOpen" width="700px" >
        <el-form ref="rechargeRef" :model="rechargeForm" :rules="rechargeRules" label-width="80px">
          <el-row>
            <el-col :span="12">
                <el-form-item label="操作类型">
                  <el-radio-group v-model="rechargeForm.type">
                      <el-radio
                      v-for="dict in doTypeList"
                      :key="dict.value"
                      :label="dict.value"
                      >{{dict.label}}</el-radio>
                  </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="操作类别" prop="doType">
                <el-select v-model="rechargeForm.doType" placeholder="请选择操作类别"   style="width: 240px;">
                    <el-option
                        v-for="dict in typeOptions"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="操作数额" prop="money">
                <el-input v-model="rechargeForm.money" placeholder="请输入操作数额"  type="number" style="width: 240px;"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="rechargeForm.remark" placeholder="请输入备注" type="textarea"/>
              </el-form-item>
            </el-col>
            </el-row>
        </el-form>
        <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRechargeThrottle">确 定</el-button>
          <el-button @click="cancels">取 消</el-button>
        </div>
      </template>
      </el-dialog>
      <el-dialog title="修改邀请人" v-model="changeOpen" width="700px" >
        <el-form ref="changeRef" :model="changeForm" :rules="changeRules" label-width="80px">
          <el-row>
            <el-form-item label="邀请人">
                <el-select
                    v-model="changeForm.inviterId"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入手机号"
                    style="width: 290px;"
                    :remote-method="remoteMethod"
                    :loading="memloading">
                    <el-option
                      v-for="item in memberOptions"
                      :key="item.memId"
                      :label="item.realname+'('+item.mobile+')'"
                      :value="item.memId">
                    </el-option>
                  </el-select>
                </el-form-item>

          </el-row>
        </el-form>
        <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitChange">确 定</el-button>
          <el-button @click="cancelChange">取 消</el-button>
        </div>
      </template>
      </el-dialog>
      <el-dialog title="拨款" v-model="transferOpen" width="700px" >
        <el-form ref="transferRef" :model="transferForm" :rules="transferRules" label-width="80px">
          <el-row>
            <el-col :span="12">
                <el-form-item label="操作类型">
                  <el-radio-group v-model="transferForm.type">
                      <el-radio
                      v-for="dict in doTypeList"
                      :key="dict.value"
                      :label="dict.value"
                      >{{dict.label}}</el-radio>
                  </el-radio-group>
                </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="操作数额" prop="money">
                <el-input v-model="transferForm.money" placeholder="请输入操作数额"  type="number" style="width: 240px;"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="transferForm.remark" placeholder="请输入备注" type="textarea"/>
              </el-form-item>
            </el-col>
            </el-row>
        </el-form>
        <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTransferThrottle">确 定</el-button>
          <el-button @click="transferCancel">取 消</el-button>
        </div>
      </template>
      </el-dialog>
  </div>
</template>

<script setup name="goodsManage">
import { getMemberLevelColumnList } from "@/api/member/level";
import { getMemberList,addMember,deleteMember,editMember,getMemberDetail,recharge,changePerson,memberTransfer} from "@/api/member/index";
import _ from 'lodash';
const { proxy } = getCurrentInstance();
const { sys_user_sex,sys_normal_disable } = proxy.useDict("sys_user_sex","sys_normal_disable");

const memberList = ref([]);

const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const memberLevelColumnList = ref([]);
const memberOptions = ref([]);
const memloading = ref(false);

const rechargeOpen =  ref(false);
const transferOpen =  ref(false);
const changeOpen =  ref(false);
const typeOptions = ref([
  {
    value:1,
    label:'金额'
  },
  {
    value:2,
    label:'饭团'
  },
  {
    value:3,
    label:'饭券'
  },
  {
    value:4,
    label:'奖金池'
  }
])

const partnerList = ref([
  {
    value:0,
    label:'否'
  },
  {
    value:1,
    label:'是'
  }
])

const doTypeList = ref([
  {
    value:1,
    label:'充值'
  },
  {
    value:2,
    label:'消费'
  }
])

const data = reactive({
 form: {},
 queryParams: {
   pageNum: 1,
   pageSize: 10,
   realname: undefined,
   mobile:undefined,
   memId:undefined
 },
 rechargeForm:{},
 changeForm:{},
 transferForm:{},
 rules: {
  realname: [
    { required: true, message: "会员姓名不能为空", trigger: "blur" }
  ],
  mobile: [
    { required: true, message: "手机号码不能为空", trigger: "blur" },
    {
        pattern: /^(1[3-9]\d{9})$|^([69]\d{7})$|^([6]\d{5})$|^(09\d{8})$/,
        message: "请输入正确的手机号码",
        trigger: "blur"
    }

  ],
  // memberLevel:[
  //   { required: true, message: "会员等级不能为空", trigger: "change" }
  // ],
  inviterId:[
    { required: true, message: "邀请人不能为空", trigger: "blur" }
  ]
 },
 rechargeRules: {
    money: [
      { required: true, message: "操作数额不能为空", trigger: ["blur","change"] }
    ],
    doType: [
      { required: true, message: "操作类别不能为空", trigger: ["blur","change"] }
    ],
    type: [
      { required: true, message: "操作类型不能为空", trigger: ["blur","change"] }
    ],
  },
  transferRules: {
    money: [
      { required: true, message: "操作数额不能为空", trigger: ["blur","change"] }
    ],
    type: [
      { required: true, message: "操作类型不能为空", trigger: ["blur","change"] }
    ],
  },
  changeRules: {
    inviterId: [
      { required: true, message: "邀请人不能为空", trigger: ["blur","change"] }
    ],

  },
});



const { queryParams, form, rules,rechargeForm,rechargeRules,changeForm,changeRules,transferForm,transferRules} = toRefs(data);

/** 查询会员等级列表 */
function getList() {
 loading.value = true;
 getMemberList(queryParams.value).then(response => {
   memberList.value = response.rows;
   total.value = response.total;
   loading.value = false;
 });
}
/** 取消按钮 */
function cancel() {
 open.value = false;
 reset();
}
/** 表单重置 */
function reset() {
 form.value = {
  memId: undefined,
  realname: undefined,
  mobile: undefined,
  nickname: undefined,
  memberLevel: undefined,
  sex: undefined,
  address: undefined,
  intro: undefined,
  signature: undefined,
  status: "0",
  isWithdraw:"0",
  partner:0
 };
 proxy.resetForm("memberRef");
}
/** 搜索按钮操作 */
function handleQuery() {
 queryParams.value.pageNum = 1;
 getList();
}
/** 重置按钮操作 */
function resetQuery() {
 proxy.resetForm("queryRef");
 handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
 ids.value = selection.map(item => item.postId);
 single.value = selection.length != 1;
 multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
 reset();
 memberOptions.value = [];
 open.value = true;
 title.value = "添加会员";
}
/** 修改按钮操作 */
function handleUpdate(row) {
 reset();
 const id =  row.memId;
 getMemberDetail(id).then(response => {
    response.data.sex = response.data.sex+'';
    response.data.status = response.data.status+'';
    response.data.isWithdraw = response.data.isWithdraw+'';
    response.data.inviterId =  parseInt(response.data.inviterId);
   form.value = response.data;
   title.value = "修改会员";
   open.value = true;
   getMemberList({realname:row.inviterName}).then(responses => {
        memberOptions.value = responses.data
        memloading.value  = false;
    });
 });
}

/** 表单重置 */
function rechargeReset() {
  rechargeForm.value = {
    memId:undefined,
    money:undefined,
    remark:undefined,
    doType:1,
    type:1
 };
 proxy.resetForm("rechargeRef");
}
/** 取消按钮 */
function cancels() {
  rechargeOpen.value = false;
 rechargeReset();
}


function handleRecharge(row){
  rechargeReset();
  rechargeForm.value.memId = row.memId
  rechargeOpen.value = true

  proxy.resetForm("rechargeRef");

}


function  submitRecharge(){
  proxy.$refs["rechargeRef"].validate(valid => {
    if (valid) {
      let amtreg = /^\d+(\.\d{1,2})?$/;

      if(!amtreg.test(rechargeForm.value.money)){
        proxy.$modal.msgError("请输入正确的金额格式！");
          return;
      }
      if(rechargeForm.value.money == 0){
        proxy.$modal.msgError("请输入正确的金额格式！");
          return;
      }
      recharge(rechargeForm.value).then(res=>{
        proxy.$modal.msgSuccess("操作成功");
        rechargeOpen.value = false;
        getList();
      })
    }
  })
}
const submitRechargeThrottle = _.throttle(() => {
  submitRecharge()
}, 2000,{trailing: false})

function  submitChange(){
  proxy.$refs["changeRef"].validate(valid => {
    if (valid) {
      changePerson(changeForm.value).then(res=>{
        proxy.$modal.msgSuccess("修改成功");
        changeOpen.value = false;
        getList();
      })
    }
  })
}
/** 取消按钮 */
function cancelChange() {
  changeOpen.value = false;
  changeReset();
}

/** 表单重置 */
function changeReset() {
  changeForm.value = {
    memId:undefined,
    inviterId:undefined,
 };
 proxy.resetForm("changeRef");
}

function changePersons(row){
  changeReset();
  changeForm.value.memId = row.memId
  changeOpen.value = true

  proxy.resetForm("changeRef");
}

function handleChange(row){
  proxy.$router.push({ path: "/member/changeLog",query: { memId: row.memId }});
}


/** 提交按钮 */
function submitForm() {
 proxy.$refs["memberRef"].validate(valid => {
   if (valid) {

     if (form.value.memId != undefined) {
      editMember(form.value).then(response => {
         proxy.$modal.msgSuccess("修改成功");
         open.value = false;
         getList();
       });
     } else {
      addMember(form.value).then(response => {
         proxy.$modal.msgSuccess("新增成功");
         open.value = false;
         getList();
       });
     }
   }
 });
}
/** 删除按钮操作 */
function handleDelete(row) {
 const id =  row.memId;
 proxy.$modal.confirm('是否确认删除名称为"' + row.realname + '"的数据项？').then(function() {
   return deleteMember(id);
 }).then(() => {
   getList();
   proxy.$modal.msgSuccess("删除成功");
 }).catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
 proxy.download("system/post/export", {
   ...queryParams.value
 }, `post_${new Date().getTime()}.xlsx`);
}

 /** 获取会员等级列表 */
 function  getMemberLevelColumnLists(){
  getMemberLevelColumnList().then((res)=>{
      memberLevelColumnList.value = res.data
  })
}
function remoteMethod(query) {
  if (query !== '') {
    memloading.value = true;
    setTimeout(() => {

      getMemberList({mobile:query}).then(response => {
        memberOptions.value = response.data
       memloading.value = false;
      });

    }, 200);
  } else {
    memberOptions.value = [];
  }
}


/** 拨款 */
function handleTransform(row){
  transferReset();
  transferForm.value.memId = row.memId
  transferOpen.value = true

  proxy.resetForm("transferRef");
}
/** 表单重置 */
function transferReset() {
 transferForm.value = {
    memId:undefined,
    money:undefined,
    remark:undefined,
    type:1
 };
 proxy.resetForm("transferRef");
}
/** 取消按钮 */
function transferCancel() {
  transferOpen.value = false;
  transferReset();
}

const submitTransferThrottle = _.throttle(() => {
  submitTransform()
}, 2000,{trailing: false})

function  submitTransform(){
  proxy.$refs["transferRef"].validate(valid => {
    if (valid) {
      let amtreg = /^\d+(\.\d{1,2})?$/;

      if(!amtreg.test(transferForm.value.money)){
        proxy.$modal.msgError("请输入正确的金额格式！");
          return;
      }
      if(transferForm.value.money == 0){
        proxy.$modal.msgError("请输入正确的金额格式！");
          return;
      }
      memberTransfer(transferForm.value).then(res=>{
        proxy.$modal.msgSuccess("操作成功");
        transferOpen.value = false;
        getList();
      })
    }
  })
}
getMemberLevelColumnLists();
getList();
</script>
<style lang="scss" scoped>
.form_box {
  // height: 60vh;
  // overflow: auto;
}
</style>
